package com.library.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.library.Mapper.BookMapper;
import com.library.Mapper.CategoryMapper;
import com.library.Mapper.LendMapper;
import com.library.pojo.Book;
import com.library.pojo.PageResult;
import com.library.service.BookService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class BookServiceImpl  implements BookService {
    @Autowired
    private BookMapper bookMapper;
    @Autowired
    private CategoryMapper categoryMapper;
    @Autowired
    private LendMapper lendMapper;

    /**
     * 分页查询书籍
     * @param page
     * @param pageSize
     * @param bookName
     * @param author
     * @param publisher
     * @return
     */
    @Override
    public PageResult pageQuery(Integer page, Integer pageSize,
                                String bookName, String author,
                                String publisher,String category) {
        PageHelper.startPage(page,pageSize);
        List<Book> result = bookMapper.list(bookName,author,publisher,category);
        Page<Book> p = (Page<Book>)result;
        return new PageResult(p.getTotal(),p.getResult());
    }

    /**
     * 添加书籍
     * @param book
     */
    @Override
    public void add(Book book) {
        book.setCreateTime(LocalDateTime.now());
        book.setUpdateTime(LocalDateTime.now());
        bookMapper.add(book);
        //在相应分类下增加对应分类的数量
        categoryMapper.update(book.getCategory());
    }

    /**
     * 删除图书，可批量删除
     * @param ids
     */
    @Override
    public void delete(List<Long> ids) {
        for (Long id : ids) {
            String category = bookMapper.getCategoryById(id);
            categoryMapper.deleteNumber(category);
        }
        bookMapper.delete(ids);
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @Override
    public Book getById(Long id) {
        Book book = bookMapper.getById(id);
        return book;
    }

    /**
     * 修改书籍信息
     * @param book
     */
    @Override
    public void update(Book book) {
        //旧书信息
        Book byId = bookMapper.getById(book.getId());
        //减少原有分类下的数量
        categoryMapper.deleteNumber(byId.getCategory());
        book.setUpdateTime(LocalDateTime.now());
        //找到借阅表中含有这本书的id
        String bookName = byId.getBookName();
        List<Long> lendIds = lendMapper.getIdByBookName(bookName);
        bookMapper.update(book);
        //在图书新分类下添加一本
        Book book1 = bookMapper.getById(book.getId());
        categoryMapper.update(book1.getCategory());
        //修改对应借阅表下的书籍
        String newBookName = book.getBookName();
        for (Long lendId : lendIds) {
            lendMapper.updateBookName(newBookName,lendId);
        }
    }
}
